import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import App from 'layout/App.js'
import './index.less';
import { Icon, Table, Pagination, FormControl, Button, Popconfirm, Breadcrumb, Modal, Label, FormGroup, Select } from 'tinper-bee';
import { doPost, init, getDatasource, design, doSyncTemplate } from './PrintTemplate.config'
import { vendorsDanger as danger, vendorsSuccess as success, vendorsFmtDate as fmtDate, vendorsTrimStr as trimStr } from 'utils/config.js';
import CommonModal from './../../components/CommonModal/index.jsx';
import PresetTemplate from './../../components/PresetTemplate/index.jsx';
import jdiwork from '../../utils/jdiwork'
let numberPerPage = 10;
// let tenantId = '';//'x61tnmfx';//'stprk896'; let tenantId = 
const Option = Select.Option;

export default class PrintTemplate extends Component {
    constructor(props) {
        super(props);

        this.state = {
            dataall: [],
            data: [],
            activePage: 1,
            items: 1,
            searchText: '',
            dsList: {},
            dsname: '',
            modelname: '',
            showSyncModal: false,
            tenantIdStr: '',
            isShowSyncBtn: this.props.type === 'sys'
        };
    }

    getListData = () => {
        let _me = this;

        doPost({ 'isAjax': 1, ieStamp: new Date().getTime(), tetantId: this.tenantId, tenantId: this.tenantId, url: '/rest/printTemplate/queryBytatent' })
            .then(function (response) {
                if (response.data.resultCode != 'busi_ex') {
                    let data = JSON.parse(response.data.result);
                    let pages = Math.ceil(data.length / numberPerPage);

                    _me.setState({
                        dataall: data,
                        items: pages
                    });

                } else {
                    danger({ 'text': response.data.exMsg });
                }
            });
    }

    componentDidMount = () => {
        let _me = this;
        if (this.props.type == 'sys') {
            console.log('sys');
            this.tenantId = '';
            this.getListData();
            this.getDatasourceAction()
        } else {
            if(document.cookie.split(';').find(cur => cur.indexOf('tenantid=') != -1)){
                this.tenantId = document.cookie.split(';').find(cur => cur.indexOf('tenantid=') != -1).split('=')[1];
                this.getListData();
                this.getDatasourceAction()
            }else {
                jdiwork().getContext((data) => {
                    this.tenantId = data.tenantid;
                    this.getListData();
                    this.getDatasourceAction()
                });
            }
        }
    }
    getDatasourceAction = () =>{
        let _me = this;
        getDatasource({ 'isAjax': 1, ieStamp: new Date().getTime(), url: '/rest/bomanage/querybytenant', tenantId: this.tenantId }).then(function (response) {
            if (response.data.resultCode != 'busi_ex') {
                let data = JSON.parse(response.data.result);

                console.log(data);

                let dsList = data.map(cur => <Option value={cur.bo_code}>{cur.bo_name}</Option>);

                _me.setState({
                    dsList: dsList,
                });

            } else {
                danger({ 'text': response.data.exMsg });
            }
        })
    }

    handleSelect = (e) => {
        this.setState({
            activePage: e
        });
        this.getListData(this.state.searchText, e);

    }


    addCatalog = () => {
        this.setState({
            showModal: true,
            operation: 'create'
        });
    }

    deleteRow = (text, e) => {
        console.log('删除行');
        let _me = this;

        doPost({ 'isAjax': 1, ieStamp: new Date().getTime(), pk_template: text, url: '/rest/printTemplate/deleteprint' })
            .then(function (response) {
                if (response.data.resultCode != 'busi_ex') {
                    let dataall = _me.state.dataall.filter(cur => cur.pk_print_template != text);

                    _me.setState({
                        dataall: dataall
                    })

                } else {
                    danger({ 'text': response.data.exMsg });
                }
            });
    }

    editRow = (record, e) => {
        console.log('编辑行');
        let url = `./print/design?tenantId=${this.tenantId}&printcode=${record.templatecode}`;

        window.open(encodeURI(url));
    }

    copyRow = (text, e) => {
        console.log('复制行');

        this.setState({
            showModal: true,
            operation: 'copy',
            pk_template: text
        });



    }

    showDetail = (record, e) => {
        console.log('查看行');
        sessionStorage.setItem("editcata", record.pkCompletedCatalog);
        window.location.href = "./workdatacatadetail.html";
    }

    handleinit = () => {
        let _me = this;
        init({ 'isAjax': 1, ieStamp: new Date().getTime(), tenantId: this.tenantId })
            .then(function (response) {
                if (response.data.resultCode != 'busi_ex') {
                    _me.getDatasourceAction();
                    success({ 'text': response.data.result });
                } else {
                    danger({ 'text': response.data.exMsg });
                }
            });
    }

    handleChange = (e) => {
        this.setState({
            modelname: e.target.value
        })
    }

    datasourceChange = (e) => {
        this.setState({
            dsname: e
        })
    }

    close = () => {
        this.setState({
            showModal: false,
            commit: false,
            dsname: '',
            modelname: ''
        });
    }

    showSyncModal = () => {
        this.setState({
            tenantIdStr: '',
            showSyncModal: true
        });
    }

    closeSyncModal = () => {
        this.setState({
            showSyncModal: false
        });
    }

    handleChangeTenStr = (e) => {
        this.setState({
            tenantIdStr: e.target.value
        });
    }

    confirmSyncTemp = () => {
        let tenantIdArr = this.state.tenantIdStr.split(/,|，/g);
        doSyncTemplate(tenantIdArr).then((res) => {
            if (res.data.resultCode != 'busi_ex') {
                success({ 'text': res.data.result });
            } else {
                danger({ 'text': res.data.exMsg });
            }
        }).then(() => {
            this.setState({
                showSyncModal: false
            });
        });
    }

    submith = () => {
        let _me = this;
        this.setState({
            commit: true
        })

        if (this.state.operation == 'create') {
            if (!(this.state.dsname && this.state.modelname)) {
                return;
            }

            let url = `./print/design?tenantId=${this.tenantId}&bocode=${this.state.dsname}&reportName=${this.state.modelname}&type=${(!this.tenantId) ? "52a7f32d-fbb3-49d5-9700-01605b80bd9c" : "48a8206f-6759-431e-bf84-e973935e2fcc"}&alias=true`;

            window.open(encodeURI(url));

            this.close();

        } else if (this.state.operation == 'copy') {
            if (!(this.state.modelname)) {
                return;
            }

            doPost({ 'isAjax': 1, ieStamp: new Date().getTime(), tenantId: this.tenantId, pk_template: this.state.pk_template, url: '/rest/printTemplate/copytemByPk', templatecode: new Date().getTime(), templatename: this.state.modelname })
                .then(function (response) {
                    if (response.data.resultCode != 'busi_ex') {
                        success({ 'text': '复制成功' });
                        _me.getListData();
                        _me.close();

                    } else {
                        danger({ 'text': response.data.exMsg });
                    }
                });
        }
    }


    render() {
        let _me = this;

        let data = this.state.dataall.slice((this.state.activePage - 1) * numberPerPage, (this.state.activePage) * numberPerPage);

        data.forEach((cur, index, arr) => {
            let temp = (index + 1).toString();
            temp = temp.length < 2 ? 0 + temp : temp;
            cur.number = temp;
            cur.key = cur.pk_print_template;
            cur.creationtime = fmtDate(cur.createtime.time);
        });

        const columns6 = [
            { title: "序号", dataIndex: "number", key: "a", width: '5%' },
            {
                title: "名称", dataIndex: "templatename", key: "b", width: 200,
                render(text, record, index) {

                    return (
                        <div className="hrowop">
                            <span onClick={_me.editRow.bind(null, record)}>{text}</span>
                        </div>
                    );
                }
            },
            { title: "创建时间", dataIndex: "creationtime", key: "e", width: 100 },
            {
                title: "操作", dataIndex: "pk_print_template", key: "f",
                render(text, record, index) {

                    return (
                        <div className="hrowop">
                            <span onClick={_me.editRow.bind(null, record)}>设计  </span>|
                            <span onClick={_me.copyRow.bind(null, text)}>  复制  </span>|
                            <Popconfirm trigger="click" placement="top" content={<div className="table-delete clearfix">
                                <i className="uf uf-exc-c hdelwarning"></i>
                                <span className="hdelspan">你确定删除该目录吗？</span>
                            </div>} onClose={_me.deleteRow.bind(null, text)} rootClose={true}>
                                <span>  删除</span>
                            </Popconfirm>
                        </div>
                    );
                }, width: 100
            }
        ];

        let nameToFill = this.state.commit && !this.state.modelname;
        let dsToFill = this.state.commit && !this.state.dsname;
        return (
            <App>
                <div className="hbodyone">
                    <div className="hbodyopecata">
                        <div className="hbodyopeleft">
                            打印模版管理
                        </div>
                        <div className="hbodyoperight">
                            {this.state.isShowSyncBtn && <Button className="hadd" colors="primary" onClick={this.showSyncModal}>模板同步</Button>}
                            <Button className="hadd" colors="primary" onClick={this.handleinit}>数据源初始化</Button>
                            <Button className="hadd" colors="primary" onClick={this.addCatalog}>创建</Button>
                        </div>
                    </div>
                    <Table columns={columns6} data={data} useFixedHeader={true} emptyText={() => '暂无数据'} />
                    <div>
                        <Pagination style={{ float: 'right', margin: '5px 0' }}
                            first
                            last
                            prev
                            next
                            boundaryLinks
                            items={this.state.items}
                            maxButtons={5}
                            activePage={this.state.activePage}
                            onSelect={this.handleSelect}
                        />
                        <div style={{ height: '35px' }}></div>
                    </div>
                </div>
                <Modal
                    className='hcreatemodal'
                    show={this.state.showModal}
                    onHide={this.close}
                    style={{ width: 450, top: 100 }}
                    backdrop={false}
                >
                    <Modal.Header className='hmodalheader' closeButton={true}>
                        创建模版
                    </Modal.Header>

                    <Modal.Body>
                        <div style={{ width: 400, margin: '0 auto', paddingLeft: 20 }}>
                            <FormGroup>
                                <Label>模版名称</Label>
                                <FormControl className={nameToFill ? 'hinputrequired hmodalinput' : 'hmodalinput'}
                                    value={this.state.modelname}
                                    onChange={this.handleChange}
                                />
                            </FormGroup>
                            <div style={{ visibility: nameToFill ? "visible" : "hidden" }}><span className="hrequired">请输入模版名称</span></div>
                            <div style={{ display: this.state.operation == 'copy' ? 'none' : 'block' }}>
                                <FormGroup>
                                    <Label>数据源</Label>
                                    <Select className={dsToFill ? 'hinputrequired hmodalinput' : 'hmodalinput'} showSearch value={this.state.dsname} placeholder="请选择数据源" allowClear={false} onChange={this.datasourceChange} optionFilterProp="children" notFoundContent="没有相关条目" dropdownMatchSelectWidth={false}  >
                                        {this.state.dsList}
                                    </Select>
                                </FormGroup>
                                <div style={{ visibility: dsToFill ? "visible" : "hidden" }}><span className="hrequired">请选择数据源</span></div>
                            </div>
                        </div>


                    </Modal.Body>

                    <Modal.Footer className="text-center">
                        <Button bordered style={{ marginRight: 20 }} onClick={this.close}>
                            取消
                        </Button>
                        <Button colors="primary" onClick={this.submith}>
                            确认
                        </Button>
                    </Modal.Footer>
                </Modal>
                <Modal
                    show={this.state.showSyncModal}
                    onHide={this.closeSyncModal}
                    size='lg'
                    style={{ top: 100 }}
                    backdrop={false}
                >
                    <Modal.Header className="text-center">
                        <Modal.Title>输入租户ID</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <div style={{ width: 300, margin: '0 auto' }}>
                            <FormGroup>
                                <FormControl
                                    value={this.state.tenantIdStr}
                                    onChange={this.handleChangeTenStr}
                                />
                            </FormGroup>
                        </div>
                    </Modal.Body>
                    <Modal.Footer className="text-center">
                        <Button bordered style={{ marginRight: 20 }} onClick={this.closeSyncModal}>
                            取消
                        </Button>
                        <Button colors="primary" onClick={this.confirmSyncTemp}>
                            确认
                        </Button>
                    </Modal.Footer>
                </Modal>
            </App>
        );
    }
}